﻿/*
Copyright (C) 2010 INOUE Hiroyuki

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

using System;
using System.Collections.Generic;

namespace CodePlex.Dombly.DiskUsage.ConsoleApplication
{
    /// <summary>
    /// SortedSet that has a fixed-size capacity.  Adding any instance 
    /// with the value minor than current Min value is ommitted.
    /// </summary>
    /// <typeparam name="T">
    /// Type of the contents, which should implement IComparable.
    /// </typeparam>
    class FixedSizeSortedSet<T> : SortedSet<T>
        where T : class, IComparable<T>
    {
        private readonly int _Size;
        public FixedSizeSortedSet(int size)
            : base(_Comparer.GetInstance())
        {
            this._Size = size;
        }
        public new bool Add(T i)
        {
            if (this.Count >= this._Size)
            {
                if (this.Comparer.Compare(i, this.Max) >= 0) return false;
                this.Remove(this.Max);
            }
            return base.Add(i);
        }
        private class _Comparer : IComparer<T>
        {
            public int Compare(T x, T y)
            {
                return x.CompareTo(y);
            }
            private _Comparer() { }
            private static _Comparer _Instance = new _Comparer();
            public static _Comparer GetInstance() { return _Instance; }
        }
    }
}
